//
//  LZLoginViewController.m
//  DoctorFAQs
//
//  Created by langZai on 2017/2/14.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "LZLoginViewController.h"
#import "LZForgetPwdViewController.h"
#import "LZLoginBottomView.h"
#import "LZRegisterBottomView.h"
#import "JTabBarController.h"
#import "LZBoundPhoneViewController.h"
#import "LZUserDealViewController.h"
#import "YJProgressHUD.h"
@interface LZLoginViewController ()<UITextFieldDelegate,UIScrollViewDelegate,UINavigationControllerDelegate>
/** 头部背景ImageView */
@property (nonatomic ,strong) UIImageView *backGroundImageView;
/** 返回按钮大叉叉 */
@property (nonatomic ,strong) UIButton *backBtn;
/** 登录按钮 */
@property (nonatomic ,strong) UIButton *loginBtn;
/** 注册按钮 */
@property (nonatomic ,strong) UIButton *registerBtn;
/** 三角形 */
@property (nonatomic ,strong) UIImageView *triangleImageView;
/** 登录底部View */
@property (nonatomic ,strong) LZLoginBottomView *loginBottomView;
/** 注册底部View */
@property (nonatomic ,strong) LZRegisterBottomView *registerBottomView;
/** scrollView */
@property (nonatomic,strong) UIScrollView *bgScrollView;
/** 倒计时时间 */
@property (nonatomic, copy) dispatch_source_t timer;

@end

@implementation LZLoginViewController



- (void)viewDidLoad {

    [super viewDidLoad];
    
    self.view.backgroundColor = KHColorFromRGB(0xffffff);
    self.navigationController.delegate = self;
    [self createHeaderImageView];
    [self.view addSubview:self.bgScrollView];
    [self createBottomUI];

}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.hidden = YES;
//}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

//- (void)viewWillDisappear:(BOOL)animated {
//    
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.hidden = NO;
//}

// 创建ScrollView
-(UIScrollView *)bgScrollView {
    if (_bgScrollView) {
        return _bgScrollView;
    }
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 225*ysIZE, SCREEN_Width, SCREEN_Height - 225*ysIZE)];
    //_bgScrollView.backgroundColor = [UIColor redColor];
    _bgScrollView.pagingEnabled = YES;
    _bgScrollView.showsHorizontalScrollIndicator = NO;
    _bgScrollView.bounces = NO;
    _bgScrollView.delegate = self;
    //_bgScrollView.userInteractionEnabled = YES;
    _bgScrollView.contentSize = CGSizeMake(SCREEN_Width*2, 0);
    return _bgScrollView;
}

// 头部背景
- (void)createHeaderImageView {
    if (!_backGroundImageView) {
        _backGroundImageView = [[UIImageView alloc] init];
        _backGroundImageView.image = [UIImage imageNamed:@"login_bg"];
        _backGroundImageView.userInteractionEnabled = YES;
        [self.view addSubview:_backGroundImageView];
        [_backGroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.sizeOffset(CGSizeMake(SCREEN_Width, 225*ysIZE));
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view);
        }];
    }
    
    //返回按钮
    _backBtn = [[UIButton alloc] init];
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"login_cross"] forState:UIControlStateNormal];
    [_backGroundImageView addSubview:_backBtn];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(25, 25));
        make.top.equalTo(_backGroundImageView).offset(15 * ysIZE);
        make.left.equalTo(_backGroundImageView).offset(15 * xsIZE);
    }];
    [_backBtn addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 上面的登录按钮
    _loginBtn = [[UIButton alloc] init];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginBtn.titleLabel.font = NEWFONT(18);
    //_loginBtn.backgroundColor = [UIColor redColor];
    _loginBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_loginBtn setTitleColor:KHColorFromRGB(0xffffff) forState:UIControlStateNormal];
    [_backGroundImageView addSubview:_loginBtn];
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_backGroundImageView).offset(75 * xsIZE);
        make.size.sizeOffset(CGSizeMake(60 *xsIZE, 40 *ysIZE));
        make.bottom.equalTo(_backGroundImageView).offset(-25 *ysIZE);
    }];
    [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 注册按钮
    _registerBtn = [[UIButton alloc] init];
    [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    _registerBtn.titleLabel.font = NEWFONT(18);
    //_registerBtn.backgroundColor = [UIColor redColor];
    _registerBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_registerBtn setTitleColor:KHColorFromRGB(0xffffff) forState:UIControlStateNormal];
    [_backGroundImageView addSubview:_registerBtn];
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(60 *xsIZE, 40 *ysIZE));
        make.bottom.equalTo(_backGroundImageView).offset(-25 *ysIZE);
        make.right.equalTo(_backGroundImageView.mas_right).offset(-75 *xsIZE);
    }];
    
    // 三角形
//    _triangleImageView = [[UIImageView alloc] initWithFrame:CGRectMake((75+(60-15)/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE)];
//    _triangleImageView.image = [UIImage imageNamed:@"login_btn_gc"];
//    [_backGroundImageView addSubview:_triangleImageView];
    
    _triangleImageView = [[UIImageView alloc] initWithFrame:CGRectMake((75+(60-15)/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE)];
    _triangleImageView.image = [UIImage imageNamed:@"login_triangle"];
    [self.backGroundImageView addSubview:_triangleImageView];
    
    
    
    // 小的分隔线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = KHColorFromRGB(0xffffff);
    [_backGroundImageView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.sizeOffset(CGSizeMake(1 *xsIZE, 15 *ysIZE));
        make.centerX.equalTo(_backGroundImageView);
        make.centerY.equalTo(_loginBtn);
    }];
    
    [_registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
}


// 下面部分
- (void)createBottomUI {
    
    // 登录下面的部分
    _loginBottomView = [[LZLoginBottomView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height-225*ysIZE)];
    _loginBottomView.phoneTextField.delegate = self;
    _loginBottomView.phoneTextField.tag = 250;

    
    //大的登录按钮点击
    [_loginBottomView.loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    // 忘记密码点击事件
    [_loginBottomView.forgetBtn addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 微信快速登录点击
    [_loginBottomView.weChatBtn addTarget:self action:@selector(weichatClick) forControlEvents:UIControlEventTouchUpInside];
    
    // QQ快速登录点击
    [_loginBottomView.qqBtn addTarget:self action:@selector(qqClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 微博快速登录点击
    [_loginBottomView.weiboBtn addTarget:self action:@selector(weiboClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bgScrollView addSubview:_loginBottomView];

    // 注册下面的部分
    _registerBottomView = [[LZRegisterBottomView alloc] initWithFrame:CGRectMake(SCREEN_Width, 0, SCREEN_Width, SCREEN_Height-225*ysIZE)];
    _registerBottomView.lzphoneTextField.delegate = self;
    _registerBottomView.lzphoneTextField.tag = 251;
    //获取验证码点击事件
    [_registerBottomView.getBtn addTarget:self action:@selector(getBtnClick) forControlEvents:UIControlEventTouchUpInside];
    // 用户协议添加点击事件
    [_registerBottomView.dealBtn addTarget:self action:@selector(dealBtnClick) forControlEvents:UIControlEventTouchUpInside];
    // 下面大的注册按钮添加点击事件
    [_registerBottomView.registerButton addTarget:self action:@selector(bigRegisterBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bgScrollView addSubview:_registerBottomView];
}

#pragma mark - UITextFieldDelegate

// 左上角返回按钮点击
- (void)backButtonClick {
//    JTabBarController * JVC = [[JTabBarController alloc]init];
//    JVC.selectedIndex = 0;
    [self dismissViewControllerAnimated:YES completion:^{
       
    }];
    
    
}

// 最上面的登录按钮点击
- (void)loginBtnClick {
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    //小三角形
    [UIView animateWithDuration:0.3 animations:^{
        self.triangleImageView.frame = CGRectMake((75+(60-15)/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE);
    }];
    
}

// 上面的小注册按钮点击
- (void)registerBtnClick {
    [self.bgScrollView setContentOffset:CGPointMake(SCREEN_Width, 0) animated:YES];
    // 小三角
    [UIView animateWithDuration:0.3 animations:^{
        self.triangleImageView.frame = CGRectMake(SCREEN_Width - (90+45/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE);
    }];
}

// 忘记密码点击
- (void)forgetBtnClick {
    LZForgetPwdViewController *forgetPwdVC = [[LZForgetPwdViewController alloc] init];
    [self.navigationController pushViewController:forgetPwdVC animated:YES];
}




// 显示十一位
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 250) {
        if (range.length + range.location > _loginBottomView.phoneTextField.text.length) {
            return NO;
        }
        NSUInteger newLenth = [_loginBottomView.phoneTextField.text length] + [string length] - range.length;
        return newLenth <= 11;
    }else {
        if (range.length + range.location > _registerBottomView.lzphoneTextField.text.length) {
            return NO;
        }
        NSUInteger newLenth = [_registerBottomView.lzphoneTextField.text length] + [string length] - range.length;
        return newLenth <= 11;
    }
}


// 真正的登录按钮点击
- (void)loginButtonClick {
    if (!Predicate(PhoneRegex,_loginBottomView.phoneTextField.text)) {
        [YJProgressHUD showMessage:@"请输入正确的手机号码" inView:self.view];
        return;
    }
    if (!Predicate(PasswordRegex,_loginBottomView.pwdTextField.text)) {
        [YJProgressHUD showMessage:@"密码格式不正确" inView:self.view];
        return;
    }
    // 登录
    NSDictionary *paramas = @{@"tel":_loginBottomView.phoneTextField.text,@"password":_loginBottomView.pwdTextField.text};
    __weak typeof(self) weakSelf = self;
    
    // 菊花
    [YJProgressHUD showProgress:@"正在登录..." inView:self.view];
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Login/login" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            
            [weakSelf saveUserInfoWithDict:dict];
            [YJProgressHUD showMessage:@"登录成功" inView:self.view];
            [weakSelf backButtonClick];
            
            // 发送成功登录的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LLoginSuccess" object:nil];
            
        }else if ([dict[@"code"] intValue] == 2) {
            [YJProgressHUD showMessage:@"该手机号未注册" inView:self.view];
        }else if ([dict[@"code"] intValue] == 0) {
            [YJProgressHUD showMessage:@"账号或密码错误" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"登录失败" inView:self.view];
    }];
}

// 通过字典保存用户信息
- (void)saveUserInfoWithDict:(NSDictionary *)dict {
    
    [LZUserInfo shareInfo].uid = dict[@"list"][@"id"];
    [LZUserInfo shareInfo].userAge = dict[@"list"][@"age"];
    [LZUserInfo shareInfo].userName = dict[@"list"][@"name"];
    [LZUserInfo shareInfo].passWord = dict[@"list"][@"password"];
    [LZUserInfo shareInfo].userSex = dict[@"list"][@"sex"];
    [LZUserInfo shareInfo].phone = dict[@"list"][@"tel"];
    [LZUserInfo shareInfo].userTime = dict[@"list"][@"time"];
    // 直接存返回的string类型的头像
    NSString * pic = dict[@"list"][@"pic"];
    NSString *iconStr = [NSString stringWithFormat:@"%@%@",IconURL,pic];
    [LZUserInfo shareInfo].userIcon = iconStr;
    [LZUserInfo saveUserInfo:[LZUserInfo shareInfo]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LogSuess" object:nil];
}

//// 通过字典保存用户信息
//- (void)saveUserInfoWithDict:(NSDictionary *)dict {
//    // 把登录状态存进沙盒
//    [[LZUserInfo shareInfo] saveLoginStateWithValue:YES Key:@"isLogin"];
//    // 用户信息存进沙盒
//    [[LZUserInfo shareInfo] saveWithDictionary:dict];
//    // 登录成功以后返回的数据给模型的属性赋值
//    
//    [[LZUserInfo shareInfo] loginSucceed];
//
//}


// 获取验证码按钮点击
- (void)getBtnClick {
    
    [YJProgressHUD showProgress:@"" inView:self.view];
    
    if (!Predicate(PhoneRegex,_registerBottomView.lzphoneTextField.text)) {
        [YJProgressHUD showMessage:@"请输入正确的手机号码" inView:self.view];
        return;
    }
    
    NSDictionary *paramas = @{@"type":@"1",@"tel":_registerBottomView.lzphoneTextField.text};
    // 获取验证码
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Login/gainCode" sucessBlock:^(id content) {
//        NSLog(@"%@",content);
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            // 返回验证码
            [YJProgressHUD showMessage:@"获取成功" inView:self.view];
        // 倒计时
        [self openCountdown];
            
        }else if ([dict[@"code"] intValue] == 2) {
            //该手机号已经注册
            [YJProgressHUD showMessage:@"该手机号已被注册" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"获取失败" inView:self.view];
    }];
    
}

// 大的注册按钮点击
- (void)bigRegisterBtnClick {
    if (!Predicate(PhoneRegex,_registerBottomView.lzphoneTextField.text)) {
        [YJProgressHUD showMessage:@"请输入正确的手机号码" inView:self.view];
        return;
    }
    if ((!Predicate(PasswordRegex, _registerBottomView.lz_pwdTextField.text))||(!Predicate(PasswordRegex, _registerBottomView.conPwdTextField.text))) {
        [YJProgressHUD showMessage:@"密码格式不正确" inView:self.view];
        return;
    }
    if (![_registerBottomView.lz_pwdTextField.text isEqualToString:_registerBottomView.conPwdTextField.text]) {
        [YJProgressHUD showMessage:@"两次密码不一致" inView:self.view];
        return;
    }
    NSDictionary *paramas = @{@"tel":_registerBottomView.lzphoneTextField.text,@"password":_registerBottomView.lz_pwdTextField.text,@"rand":_registerBottomView.safeCodeTextField.text};
    __weak typeof(self) weakSelf = self;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"Login/zhuce" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            // 注册成功以后跳转登录界面
            // 清空注册信息
            [weakSelf removeInfo];
            [weakSelf loginBtnClick];
        }
        if ([dict[@"code"] intValue] == 2) {
            //手机号被注册
            [YJProgressHUD showMessage:@"验证码错误" inView:self.view];
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"注册失败" inView:self.view];
    }];
    
}

// 清空注册信息
- (void)removeInfo {
    _registerBottomView.lzphoneTextField.text = @"";
    _registerBottomView.safeCodeTextField.text = @"";
    _registerBottomView.lz_pwdTextField.text = @"";
    _registerBottomView.conPwdTextField.text = @"";
    dispatch_source_cancel(_timer);
    [self.registerBottomView.getBtn setTitle:@"获取" forState:UIControlStateNormal];
    [self.registerBottomView.getBtn setTitleColor:KHGreenColor forState:UIControlStateNormal];
    self.registerBottomView.getBtn.userInteractionEnabled = YES;
}


// 用户协议点击
- (void)dealBtnClick {
    NSLog(@"用户协议");
    LZUserDealViewController *userDealVC = [[LZUserDealViewController alloc] init];
    [self.navigationController pushViewController:userDealVC animated:YES];
}

// 微信快速登录点击
- (void)weichatClick {
    NSLog(@"快速登录微信");
    LZBoundPhoneViewController *boundPhoneVC = [[LZBoundPhoneViewController alloc] init];
    [self.navigationController pushViewController:boundPhoneVC animated:YES];
}
//qq快速登录点击
- (void)qqClick {
    NSLog(@"快速登录QQ");
    LZBoundPhoneViewController *boundPhoneVC = [[LZBoundPhoneViewController alloc] init];
    [self.navigationController pushViewController:boundPhoneVC animated:YES];
}
// 微博快速登录点击
- (void)weiboClick {
    NSLog(@"快速登录微博");
    LZBoundPhoneViewController *boundPhoneVC = [[LZBoundPhoneViewController alloc] init];
    [self.navigationController pushViewController:boundPhoneVC animated:YES];
}

// 按钮倒计时方法
-(void)openCountdown{
    __block NSInteger time = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.registerBottomView.getBtn setTitle:@"获取" forState:UIControlStateNormal];
                [self.registerBottomView.getBtn setTitleColor:KHGreenColor forState:UIControlStateNormal];
                self.registerBottomView.getBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.registerBottomView.getBtn setTitle:[NSString stringWithFormat:@"%.2d秒", seconds] forState:UIControlStateNormal];
                [self.registerBottomView.getBtn setTitleColor:KHGaryColor forState:UIControlStateNormal];
                self.registerBottomView.getBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - scrollViewDelegate
// 处理小三角形(拖拽结束以后调用)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (_bgScrollView.contentOffset.x == 0) {
        // 三角形在左边
        [UIView animateWithDuration:0.1 animations:^{
            self.triangleImageView.frame = CGRectMake((75+(60-15)/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE);
        }];
    }else {
        [UIView animateWithDuration:0.1 animations:^{
            self.triangleImageView.frame = CGRectMake(SCREEN_Width - (90+45/2)*xsIZE, 217*ysIZE, 15*xsIZE, 8*ysIZE);
        }];
        
    }
    
    
}





@end
